<!--
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-13 09:48:34
 * @LastEditTime: 2023-06-26 18:40:48
-->
<script lang="ts" setup name="RoleEditModal">
import { _, ikStore } from 'iking-utils'
import type { FormInstance } from 'element-plus'
import type { PropType, Ref } from 'vue'
import { useFormRules } from '@g/hooks/use-rules'
import { roleApi } from '@/MainApp/apis/role'
import type { RoleFormState } from '@/global/enums/role'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '新增角色'
  },
  editData: {
    type: Object as PropType<RoleFormState | null>,
    default: () => null
  }
})
const emits = defineEmits<{
  (e: 'update:visible', visible: Boolean): void
  (e: 'dataChange'): void
}>()
const { dialog, t } = useConfig()
const { lenContent, lenName } = useLength()
const { msgSuccess, msgError } = useMessage()
const formKey = {
  name: '',
  remark: '',
  dataScopeCodes: [] as Array<string>,
  sortOrder: 0,
  dataScopeType: ''
}

// 表单、编辑状态
const loading = ref(false)
const isEditing = computed(() => props.editData !== null)
const refForm: Ref<null | FormInstance> = ref(null)
const roleForm = ref<RoleFormState>({ ...formKey })
const rules = useFormRules([
  { key: 'name', required: true, trigger: 'blur', msg: '请输入角色名称' },
  { key: 'dataScopeType', required: true, trigger: 'change', msg: '请选择数据权限类型' },
  { key: 'remark', required: false, trigger: 'blur', msg: '请输入角色描述' },
  {
    key: 'dataScopeCodes',
    required: true,
    trigger: 'change',
    msg: '请选择部门',
    validator: (rule: any, value: any, cb: any) => {
      if (value.length === 0)
        cb('请选择部门')
      else
        cb()
    }
  }
])

const dVisible = ref(false)
const dataScopeTypes = computed(() => {
  const dict = ikStore.local.getItem(ELocal.DICTIONARY)
  return dict?.DATA_SCOPE?.map((d: { label: any; id: any; value: string; }) => {
    return { label: d.label, value: d.value }
  })
})
watch(
  () => props.visible,
  async (bool: any) => {
    dVisible.value = bool
    if (!bool)
      return

    if (props.editData) {
      roleForm.value = _.cloneDeep(props.editData as typeof formKey)
    }
    else {
      roleForm.value = _.cloneDeep(formKey)
      refForm.value && refForm.value?.resetFields()
    }
  }
)

// 关闭弹窗
const handleClose = () => {
  refForm.value && refForm.value?.resetFields()
  emits('update:visible', false)
}
// 确认提交
const handConfirm = () => {
  refForm.value?.validate(async valid => {
    if (valid) {
      loading.value = true
      const { success, msg } = isEditing.value
        ? await roleApi.updateRole(roleForm.value)
        : await roleApi.addRole({
          ...roleForm.value,
          parentId: roleForm.value?.parentId || null
        })
      if (success) {
        handleClose()
        emits('dataChange')
        msgSuccess(msg)
      }
      else {
        msgError(msg)
      }
      loading.value = false
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="dVisible"
    :title="isEditing ? '修改角色' : '新增角色'"
    draggable
    :width="dialog.sl"
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <el-form
      ref="refForm"
      :model="roleForm"
      :rules="rules"
      label-width="120px"
      label-position="top"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model.trim="roleForm.name"
          :maxlength="lenName"
          show-word-limit
          placeholder="请输入角色名称"
        />
      </el-form-item>
      <el-form-item label="数据权限类型" prop="dataScopeType">
        <el-select v-model="roleForm.dataScopeType" placeholder="请选择数据权限类型">
          <el-option
            v-for="type in dataScopeTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="roleForm.dataScopeType === 'DEFINE'"
        label="指定部门"
        prop="dataScopeCodes"
      >
        <IkSelectDep
          v-model="roleForm.dataScopeCodes"
          placeholder="请选择部门"
          multiple
          check-strictly
          show-checkbox
        />
      </el-form-item>
      <el-form-item label="角色描述" prop="remark">
        <el-input
          v-model.trim="roleForm.remark"
          :maxlength="lenContent"
          type="textarea"
          placeholder="请输入角色描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        bg
        text
        @click="handleClose"
      >
        {{ t("action.cancel") }}
      </el-button>
      <el-button
        type="primary"
        bg
        :loading="loading"
        @click="handConfirm"
      >
        {{ t("action.sure") }}
      </el-button>
    </template>
  </el-dialog>
</template>
